package com.itany.shop.controller;

import com.itany.shop.entity.Item;
import com.itany.shop.entity.Product;
import com.itany.shop.entity.User;
import com.itany.shop.exception.ProductNotExistException;
import com.itany.shop.exception.RequestParameterErrorException;
import com.itany.shop.exception.UserNotExistException;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.service.CartService;
import com.itany.shop.service.ProductService;
import com.itany.shop.vo.Cart;

import java.util.List;
import java.util.Scanner;

/**
 * @author MissChen
 * @date 2024年04月01日 10:56
 */
public class MainController {
    //当前登录的用户
    private User user;
    //当用户成功登录进来之后，给用户一个购物车
    private Cart cart=new Cart();
    private Scanner sc=new Scanner(System.in);

    private ProductService productService = (ProductService) ObjectFactory.getObject("productService");
    private CartService cartService = (CartService) ObjectFactory.getObject("cartService");

    public MainController(User user) {
        this.user = user;
    }

    public void showMenu(){
        System.out.println("-----------欢迎来到登录商城管理系统------------");
        System.out.print("请选择服务(1.加入购物车 2.查看购物车)");
        int choice=sc.nextInt();
        switch (choice){
            case 1:
                addCart();
                break;
            case 2:
                showCart();
                break;
        }
    }

    public void addCart(){
        List<Product> products=productService.findAll();
        if(!products.isEmpty()){
            System.out.println("商品编号\t商品名称\t商品单价");
            for(Product product:products){
                System.out.println(product.getId() + "\t" + product.getName() + "\t" + product.getPrice());
            }
        }
        System.out.print("请输入需要加入购物车的商品编号:");
        int id=sc.nextInt();
        try {
            cartService.addCart(cart,id);
            System.out.println("提示:添加购物车成功!");
        } catch (UserNotExistException e) {
            e.printStackTrace();
            System.out.println("添加购物车失败，失败原因:"+e.getMessage());
        } catch (RequestParameterErrorException e) {
            e.printStackTrace();
            System.out.println("添加购物车失败，失败原因:"+e.getMessage());
        } catch (ProductNotExistException e) {
            e.printStackTrace();
            System.out.println("添加购物车失败，失败原因:"+e.getMessage());
        }
        showMenu();

    }
    public void showCart(){
        System.out.println("商品编号\t商品名称\t商品数量\t总价");
        List<Item> items=cart.getItems();
        System.out.println(items.size());
       for(Item item:items){

           System.out.println(item.getProduct().getId()+"\t"+item.getProduct().getName()+"\t"+item.getNum()+"\t"+item.getPrice());
       }
        showMenu();
    }
}
